$(function () {
  var form = $("form");
  var username = form.find('input[name="username"]');
  var password = form.find('input[name="password"]');
  var errorDisplay = $(".error");
  var userRegex = /^[a-z0-9]\w{3,11}$/;
  var passRegex = /\w{6,12}/;

  form.on("submit", function (e) {
    e.preventDefault();
    var usernameValue = username.val();
    var passwordValue = password.val();
    var isValid = true;

    errorDisplay.empty();

    if (!usernameValue) {
      showError("用户名不能为空。");
      isValid = false;
    } else if (!userRegex.test(usernameValue)) {
      showError("用户名格式不正确。");
      isValid = false;
    }

    if (isValid && !passwordValue) {
      showError("密码不能为空。");
    } else if (isValid && !passRegex.test(passwordValue)) {
      showError("密码应为6-12位字母或数字。");
    }

    if (isValid) {
      axios
        .post("http://localhost:9000/users/login", {
          username: usernameValue,
          password: passwordValue,
        })
        .then(function (response) {
          if (response.data.code === 1) {
            sessionStorage.setItem("nickname", response.data.user.nickname);
            sessionStorage.setItem("id", response.data.user.id);
            sessionStorage.setItem("token", response.data.token);
            window.location.href = "index.html";
          } else {
            showError(response.data.message);
          }
        })
        .catch(function (error) {
          showError("登录失败");
        });
    }
  });

  function showError(message) {
    errorDisplay.text(message).show();
  }
});
